interface MainModeOp {
	escExit?: boolean;
	rightExit?: boolean;
	touchendExit?: boolean;
}

class MainMode {
	Main: egret.DisplayObject;

	constructor(Main: egret.DisplayObject) {
		this.Main = Main;
		Main.addEventListener(egret.TouchEvent.TOUCH_END, this.onTouchEndMain, this);
	}

	mod = '';

	modExit: () => void;

	modOption: MainModeOp;

	changeMode(mod: string, op: MainModeOp, exit: () => void): void {
		if (this.mod !== mod) {
			this.exitMode('force');
		}

		this.mod = mod;
		this.modOption = op;
		this.modExit = exit;
	}

	leaveMode(mode: string): boolean {
		if (this.mod !== mode) {
			return false;
		}
		this._exitMode();
		return true;
	}

	exitMode(op: string): void {
		if (this.mod) {
			if (op === 'esc' && !this.modOption.escExit) {
				return;
			}
			if (op === 'right' && !this.modOption.rightExit) {
				return;
			}
			if (op === 'touchend' && !this.modOption.touchendExit) {
				return;
			}
			this._exitMode();
		}
	}

	_exitMode(): void {
		this.mod = '';
		const func = this.modExit;
		this.modExit = null;
		if (func) {
			func();
		}
	}

	onMouseRightDown(): void {
		this.exitMode('right');
	}

	private onTouchEndMain(e: egret.TouchEvent): void {
		this.exitMode('touchend');
	}

	onEscape(): boolean {
		if (this.mod) {
			this.exitMode('escape');
			return true;
		}
		return false;
	}
}
